package com.zzyl.job;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.json.JSONUtil;
import com.zzyl.constant.CacheConstants;
import com.zzyl.entity.AlertRule;
import com.zzyl.mapper.AlertRuleMapper;
import com.zzyl.service.AlertRuleService;
import com.zzyl.vo.DeviceDataVo;
import lombok.RequiredArgsConstructor;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;

@Component
@RequiredArgsConstructor
public class AlertJob {
    private final AlertRuleMapper alertRuleMapper;
    private final AlertRuleService alertRuleService;
    private final RedisTemplate<String, String> redisTemplate;


    @Scheduled(cron = "0,30 * * * * ?")
    public void alert() {
        //1. 查询所有规则,非空判断
        List<AlertRule> alertRules = alertRuleMapper.selectByFunctionId(null, null, null);
        if (CollUtil.isEmpty(alertRules)) {
            return;
        }
        //2. 查询所有设备数据,非空判断
        List<Object> jsonObj = redisTemplate.opsForHash().values(CacheConstants.IOT_DEVICE_LAST_DATA_KEY);
        if (CollUtil.isEmpty(jsonObj)) {
            return;
        }
        //3. 反序列化设备数据
        List<DeviceDataVo> deviceDataVos = new ArrayList<>();
        jsonObj.forEach(json ->
                deviceDataVos.addAll(JSONUtil.toList(JSONUtil.toJsonStr(json), DeviceDataVo.class))
        );
        //4. 数据报警处理器: 校验每一条数据是否报警
        deviceDataVos.forEach(deviceDataVo -> alertRuleService.alertFilter(deviceDataVo));
    }

}
